package docker

import (
	"context"
	model "docker/model/mongo"
	types2 "docker/model/types"
	"fmt"
	"github.com/jinzhu/copier"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"strings"

	"docker/internal/svc"
	"docker/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GenerateDockerRunCmdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGenerateDockerRunCmdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GenerateDockerRunCmdLogic {
	return &GenerateDockerRunCmdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GenerateDockerRunCmdLogic) GenerateDockerRunCmd(req *types.DockerRunReq) (resp *types.StringResp, err error) {
	ctx := l.svcCtx
	var dr model.DockerRun
	err = copier.Copy(&dr, req)
	if err != nil {
		return nil, err
	}
	cmd := types2.DockerCmdRun.String()

	if req.D {
		cmd = fmt.Sprintf("%s %s", cmd, "-d")
	}
	if len(req.Ports) != 0 {
		for k, v := range req.Ports {
			// docker run -p 90:90
			cmd = fmt.Sprintf("%s  %s %s:%s", cmd, "-p", k, v)
		}
	}
	if len(req.Volumes) != 0 {
		for k, v := range req.Volumes {
			// docker run -v /aa:/aa
			cmd = fmt.Sprintf("%s  %s %s:%s", cmd, "-v", k, v)
		}
	}

	containerName := req.ContainerName
	if len(containerName) == 0 {
		if strings.Contains(req.ImageName, ":") {
			index := strings.LastIndex(req.ImageName, ":")
			containerName = req.ImageName[:index]
		} else {
			containerName = req.ImageName
		}
	}
	cmd = fmt.Sprintf("%s  %s %s", cmd, "--name", containerName)
	cmd = fmt.Sprintf("%s  %s", cmd, req.ImageName)
	dr.Cmd = cmd

	if len(req.Id) == 0 {
		err = ctx.DockerRunModel.Insert(l.ctx, &dr)
	} else {
		objectID, err := primitive.ObjectIDFromHex(req.Id)
		if err == nil {
			dr.ID = objectID
			_, err = ctx.DockerRunModel.Update(l.ctx, &dr)
		}
	}

	return &types.StringResp{
		Result: types.Result{
			Code:    200,
			Message: "",
			ExtInfo: "",
		},
		Data: cmd,
	}, err
}
